package com.gy.boot.common.util;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTool {
	public final static String PATTERN_TIME = "yyyy-MM-dd HH:mm:ss";
	
	/**
	 * 转换时间为String
	 * */
	public static String format(Date date, String pattern) {
		date = date == null ? new Date() : date;
		pattern = BlankUtil.isBlank(pattern) ? PATTERN_TIME :pattern;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
		return simpleDateFormat.format(date);
	}
	/**
	 * 转换String时间为Date
	 * */
	public static Date parse(String date, String pattern) {
		if (BlankUtil.isBlank(date)) {
			return null;
		}
		pattern = BlankUtil.isBlank(pattern) ? PATTERN_TIME :pattern;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
		try {
			return simpleDateFormat.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取单元格时间; yyyy-MM-dd
	 * @param val Excel单元格时间日期:  34094,  yyyy/MM/dd, yyyy/M/d, ...等格式
	 * */
	public static String getCellDayValue(String val) {
		if (BlankUtil.isBlank(val)) {
			return null;
		}
		try {
			if (val.contains("/")) {
                if (val.substring(val.lastIndexOf("/")).length() == 3) {
                    return DateUtil.parse(val, "M/d/yy").toDateStr();
                }
				return DateUtil.parse(val, "yyyy/M/d").toDateStr();
			}
			if (val.contains("-")) {
				return DateUtil.parse(val, "yyyy-M-d").toDateStr();
			}
			if (val.contains("年")) {
				return DateUtil.parse(val, "yyyy年M月d日").toDateStr();
			}
			if (NumberUtil.isInteger(val)) {
			    int valI = Integer.parseInt(val);
                DateTime date1900 = DateUtil.parseDate("1900-01-01");
                return date1900.offset(DateField.DAY_OF_YEAR, valI-2).toDateStr();
			}
		} catch (Exception e) {
			throw new RuntimeException("日期格式错误,请检查日期格式");
		}
		return null;
	}

	
}
